/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: SysUserService.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	2015年1月20日
 */
package com.sirdc.modules.sys.service;

import java.util.ArrayList;
import java.util.List;

import com.sirdc.modules.core.exceptions.UserExistException;
import com.sirdc.modules.sys.entity.SysDept;

import com.sirdc.modules.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.core.exceptions.ServiceException;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.dao.SysUserDao;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.util.SysGlobals;
import com.sirdc.modules.sys.util.UserUtils;

/**
 * @version Revision: 0.0.1
 * @author: weihuang.peng
 * @Date: 2015年1月20日
 */
@Service
public class SysUserService extends StringPKService<SysUser> {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysTableService tableService;

    @Override
    protected BaseDao<SysUser, String> getDao() {
        return sysUserDao;
    }

    public List<SysUserDataBean> queryOnDatabean(SysUserFilter filter) {
        filter.setSuperAdmin(UserUtils.isSuperAdmin());

        List<SysUser> users = sysUserDao.queryFilter(filter);
        List<SysUserDataBean> dataBeans = new ArrayList<SysUserDataBean>();
        for (SysUser sysUser : users) {
            SysLogin login = sysLoginService.getById(sysUser.getSysId());
            SysUserDataBean dataBean = dealWithSysUserData(login,sysUser);
            dataBeans.add(dataBean);
        }
        return dataBeans;
    }

    public List<SysUserDataBean> queryOnDatabeanNoPage(SysUserFilter filter) {
        filter.setSuperAdmin(UserUtils.isSuperAdmin());
        List<SysUser> users = sysUserDao.queryFilterNoPage(filter);
        List<SysUserDataBean> dataBeans = new ArrayList<SysUserDataBean>();
        for (SysUser sysUser : users) {
            SysLogin login = sysLoginService.getById(sysUser.getSysId());
            SysUserDataBean dataBean = dealWithSysUserData(login,sysUser);
            dataBeans.add(dataBean);
        }
        return dataBeans;
    }

    public SysUserDataBean getEntityById(String id)
    {
        SysUser user = this.getById(id);
        SysLogin login = sysLoginService.getById(user.getSysId());
        SysUserDataBean bean = dealWithSysUserData(login, user);
        return bean;
    }

    public SysUserDataBean dealWithSysUserData(SysLogin login, SysUser sysUser){
        SysUserDataBean dataBean = new SysUserDataBean();
        dataBean.setMobile(sysUser.getMobile());
        dataBean.setBirthday(sysUser.getBirthday());
        dataBean.setDemo(sysUser.getDemo());
        dataBean.setPosition(sysUser.getPosition());
        dataBean.setEmail(sysUser.getAddress());
        dataBean.setFloorId(sysUser.getFloorId());
        dataBean.setGender(sysUser.getGender());
        dataBean.setName(sysUser.getName());
        dataBean.setPassword(login.getPassword());
        dataBean.setNativeAddr(sysUser.getNativeAddr());
        dataBean.setUsername(login.getUsername());
        dataBean.setDeptId(login.getDeptId());
        dataBean.setRoleId(login.getRoleId());
        dataBean.setSysId(login.getSysId());
        dataBean.setUserSort(login.getUserSort());
        return dataBean;
    }




    @Override
    protected void beforeSave(SysUser entity) {
        entity.setSysId(entity.getUserId());
    }

    public SysLogin saveUserLogin(SysUserDataBean databean) {

        databean.setUserId(tableService.updateMaxSysId("t_sys_user", null));
        //检测用户是否已经存在
        if (sysLoginService.isExistForUsername(databean.getUsername())) {
            throw new UserExistException(databean.getUsername());
        }

        //保存用户信息
        SysUser user = new SysUser();
        user.setUserId(databean.getUserId());
        user.setSysId(databean.getUserId());
        user.setBirthday(databean.getBirthday());
        user.setDemo(databean.getDemo());
        user.setPosition(databean.getPosition());
        user.setName(databean.getName());
        user.setGender(databean.getGender());
        user.setNativeAddr(databean.getNativeAddr());
        user.setState(SysGlobals.AccountStates.NOMAL);//状态为正常
        user.setIdCard(databean.getIdCard());
        user.setAddress(databean.getEmail());
        user.setMobile(databean.getMobile());
        sysUserDao.save(user);

        //保存登陆信息
        SysLogin login = new SysLogin();
        login.setUsername(databean.getUsername());
        login.setDeptId(databean.getDeptId());
        SysDept sysDept = deptService.getById(databean.getDeptId());
        boolean isDuChaGroup = sysDept.getDeptEnname().startsWith("dc_");
        if(isDuChaGroup)
        {
            login.setUserType(1);
        }
        login.setPassword(databean.getPassword());
        login.setRoleId(databean.getRoleId());
        login.setSysId(user.getUserId());
        sysLoginService.save(login);
        return login;
    }


    @Override
    public void batchDelete(List<String> ids) {
        sysUserDao.batchDeleteUser(ids);
        sysLoginService.batchDeleteLogin(ids);
    }

    /**
     * 获取用户对象
     *
     * @param id
     * @return
     */
    public SysUserDataBean getUserDataBeanById(String id) {
        SysUser sysUser = getById(id);
        if (sysUser == null) {
            throw new ServiceException("object is empty");
        }
        SysLogin sysLogin = sysLoginService.getById(id);
        SysUserDataBean databean = new SysUserDataBean();
        databean.setUserId(sysUser.getUserId());
        databean.setBirthday(sysUser.getBirthday());
        databean.setDemo(sysUser.getDemo());
        databean.setGender(sysUser.getGender());
        databean.setImage(sysUser.getImage());
        databean.setName(sysUser.getName());
        databean.setNativeAddr(sysUser.getNativeAddr());
        databean.setFloorId(sysUser.getFloorId());
        databean.setRoleId(sysLogin.getRoleId());
        databean.setPosition(sysUser.getPosition());
        databean.setDeptId(sysLogin.getDeptId());
        databean.setPassword(sysLogin.getPassword());
        databean.setIdCard(sysUser.getIdCard());
        databean.setUsername(sysLogin.getUsername());
        databean.setEmail(sysUser.getAddress());
        databean.setMobile(sysUser.getMobile());
        databean.setNation(sysUser.getNation());
        databean.setUserSort(sysLogin.getUserSort());
        databean.setPoliticalOutlook(sysUser.getPoliticalOutlook());

        return databean;
    }

    /**
     * @param databean
     * @author: weihuang.peng
     */
    public void updateUserLogin(SysUserDataBean databean) throws ServiceException {
        //更新用户信息
        SysUser user = getById(databean.getUserId());
        if ("公共账号".equals(user.getPosition()) && !user.getPosition().equals(databean.getPosition())) {
            throw new ServiceException("公共账号默认职务无法修改");
        }
        if (databean.getBirthday() != null) {
            user.setBirthday(databean.getBirthday());
        }
        if (databean.getDemo() != null) {
            user.setDemo(databean.getDemo());
        }
        if (databean.getPosition() != null) {
            user.setPosition(databean.getPosition());
        }
        if (databean.getName() != null) {
            user.setName(databean.getName());
        }
        if (databean.getGender() != null) {
            user.setGender(databean.getGender());
        }
        if (databean.getNativeAddr() != null) {
            user.setNativeAddr(databean.getNativeAddr());
        }
        if (databean.getIdCard() != null) {
            user.setIdCard(databean.getIdCard());
        }
        if (databean.getMobile() != null) {
            user.setMobile(databean.getMobile());
        }
        if (databean.getEmail() != null) {
            user.setAddress(databean.getEmail());
        }
        if (databean.getImage() != null) {
            user.setImage(databean.getImage());
        }
        if (databean.getNation() != null) {
            user.setNation(databean.getNation());
        }
        if (databean.getPoliticalOutlook() != null) {
            user.setPoliticalOutlook(databean.getPoliticalOutlook());
        }
        merge(user);
        if (StringUtils.isBlank(databean.getDeptId())) {
            return;
        }
        //更新登陆信息
        sysLoginService.updateLogin(databean);
    }

    /**
     * 更新密码
     *
     * @param databean
     */
    public void updatePassword(SysUserDataBean databean) {
        sysLoginService.updatePassword(databean);
    }

    /**
     * 通过部门和角色查询用户登陆id
     *
     * @param filter
     * @return
     */
    public List<String> queryLoginByRoleDept(SysUserFilter filter) {
        return sysLoginService.queryLoginByRoleDept(filter);
    }

    /**
     * 获取用户登陆信息
     *
     * @param sysId
     * @return
     */
    public SysLogin getSysLoginById(String sysId) {
        return sysLoginService.getById(sysId);
    }

    /**
     * 获取加密后的密码
     *
     * @param password
     * @param salt
     * @return
     */
    public String getEncryPass(String password, String salt) {
        return sysLoginService.getEncryPass(password, salt);
    }


    /**
     * 将状态码和信息输出给界面
     *
     * @param code
     * @param msg
     * @return
     */
    public Message coverMessage(String code, String msg) {
        Message message = new Message();
        message.setCode(code);
        message.setMessage(msg);
        return message;
    }

    public List<SysUser> query(SysUserFilter filter) {
        return sysUserDao.query(filter);
    }

    /**
     * 根据姓名查找
     *
     * @param names
     * @return
     */
    public List<SysUser> getByInName(String[] names) {
        return sysUserDao.getByInName(names);
    }

    public List<SysUser> queryGet(List<String> ids) {
        return sysUserDao.queryGet(ids);
    }

    public List<SysUser> getbyName(String name)
    {
        return sysUserDao.getByName(name);
    }


    /**
     * 根据用户手机号码查询所有信息
     *
     * @param mobile
     * @return
     */
    public List<SysUserDataBean> queryUserDateBeans(String mobile) {
        List<SysUserDataBean> userDataBeans = new ArrayList<>();
        List<SysUser> userList = sysUserDao.getByMobile(mobile);
        for (SysUser sysUser : userList) {
            SysUserDataBean dataBean = new SysUserDataBean();
            SysLogin sysLogin = sysLoginService.getById(sysUser.getSysId());
            SysDept dept = deptService.getById(sysLogin.getDeptId());
            if ("/01/".equals(dept.getDeptRelation())) {
                dataBean.setDeptType("督查组");
            } else if ("/02/201/".equals(dept.getDeptRelation()) || "/02/202/".equals(dept.getDeptRelation())) {
                dataBean.setDeptType("承办单位");
            }
            dataBean.setSysId(sysUser.getSysId());
            dataBean.setUserId(sysUser.getUserId());
            dataBean.setBirthday(sysUser.getBirthday());
            dataBean.setDemo(sysUser.getDemo());
            dataBean.setGender(sysUser.getGender());
            dataBean.setImage(sysUser.getImage());
            dataBean.setNativeAddr(sysUser.getNativeAddr());
            dataBean.setFloorId(sysUser.getFloorId());
            dataBean.setPassword(sysLogin.getPassword());
            dataBean.setIdCard(sysUser.getIdCard());
            dataBean.setEmail(sysUser.getAddress());
            dataBean.setNation(sysUser.getNation());
            dataBean.setPoliticalOutlook(sysUser.getPoliticalOutlook());
            dataBean.setName(sysUser.getName());//姓名（昵称）
            dataBean.setMobile(mobile);
            dataBean.setPosition(sysUser.getPosition());
            dataBean.setDeptId(sysLogin.getDeptId());
            dataBean.setDeptName(dept.getDeptName());
            dataBean.setUsername(sysLogin.getUsername());
            String roleId = sysLogin.getRoleId();
            String role = "01".equals(roleId) ? "县领导" : "02".equals(roleId) ? "主要领导" : "03".equals(roleId) ? "分管领导" : "04".equals(roleId) ? "经办人" : "10".equals(roleId) ? "县主官" : "20".equals(roleId) ? "管理员" : "未知";
            dataBean.setRole(role);
            dataBean.setRoleId(roleId);
            dataBean.setDeptCode(dept.getDeptId());
            userDataBeans.add(dataBean);
        }
        return userDataBeans;
    }
}

